package kz.kstu.scantest.app.util.locator;

import kz.kstu.scantest.business.client.config.Configuration;
import kz.kstu.scantest.business.common.exception.ServerNotFoundException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;

/**
 * @author Filipp_Stankevich
 *         created: 28.07.11 21:23
 */
public class EJBRemoteServiceLocator extends AbstractServiceLocator {

    private final static String REMOTE_BEAN_POSTFIX = "Remote";

    private final static String CONTEXT_FACTORY = "org.openejb.client.RemoteInitialContextFactory";
    private final static String PROVIDER_PREFIX = "ejbd://";

    private InitialContext initialContext;

    public EJBRemoteServiceLocator() {}

    @Override
    protected String getServiceFullName(String serviceName) {
        return serviceName + REMOTE_BEAN_POSTFIX;
    }

    @Override
    protected InitialContext getInitialContext() {
        if (initialContext == null) {
            String host = Configuration.getInstance().getParameter(Configuration.HOST_PARAM_NAME);
            String port = Configuration.getInstance().getParameter(Configuration.PORT_PARAM_NAME);
            String providerUrl =  PROVIDER_PREFIX +  host + ":" + port;
            Properties properties = new Properties();
            properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY);
            properties.setProperty(Context.PROVIDER_URL, providerUrl);
            try {
                initialContext = new InitialContext(properties);
            } catch (NamingException e) {
                throw new ServerNotFoundException(e.getMessage(), e);
            }
        }
        return initialContext;
    }
}
